/*
 *
 * C++ MaJiang for 血流红中
 *
 * TuyooGame, 2021
 * zhouxin@tuyoogame.com
 *
 */
#ifndef __MJ_CACHE__
#define __MJ_CACHE__
#include <map>
#include <cstring>
#include"xueliuhz/fan.h"
#include"xueliuhz/card.h"

using namespace std;

//#define MAX_CACHE_SIZE 160
#define MAX_CACHE_SIZE 1024*1024

typedef enum _cache_ret {
    CACHE_HIT = 1,
    CACHE_INSERT_NOTFULL = 2,
    CACHE_INSERT_FULL = 3,
    CACHE_NEED_NOT_INSERT = 0, 
    CACHE_ERROR_INPUT = -1,
    CACHE_ERROR_UNCOMPRESS = -2,
    CACHE_ERROR_COMPRESS = -3
} MJ_CACHE_RET;

class MJCache {
public:
    //记录mfihash对应的输入buffer，备查
    map<uint32_t, string> _mj_hu_input {};
    //key: MFIHash, value: mj_hu_result buffer
    map<uint32_t, string> _mj_hu_cache;
    //key: hasTing run clock, value: MFIHash
    //map本身是有顺序的，利用这个特性保留最慢的MAX_CACHE_SIZE个结果
    multimap<uint32_t, uint32_t, greater<uint32_t>> _has_ting_clock; 

    pthread_mutex_t _hu_cache_lock;

    MJCache();
    ~MJCache();

    //如果输入不在cache中，计算hasTing并插入cache，
    //保持最耗时的牌局在cache中，返回结果放在xc中
    MJ_CACHE_RET getFromCache(XueLiuHZCard *xc);
    void dumpCache(const char *path, bool isbin);
    void loadCache(const char *path, bool isbin);
    //测试内存占用
    void testCacheMem();
};

#endif

